from OWRpy import *
import redRi18n
_ = redRi18n.get_(package = 'base')

import signals 
import redRGUI 

class cophenetic(OWRpy): 
    globalSettingsList = ['commit']
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)

        # R code for generating the coldiss plot
        self.R('source(\''+unicode(os.path.join(redREnviron.directoryNames['libraryDir'], 'ecology', 'widgets', 'shepardCophCor.R')).replace('\\', '//')+'\')')
        
        
        # R variables
        self.setRvariableNames(["cophenetic_cor"])
        self.setRvariableNames(["cophenetic_dist"])
        
        # Python variables
        self.data = {}
        self.RFunctionParam_clust = ''
        self.RFunctionParam_diss = ''
        
        #Inputs
        self.inputs.addInput('id0', 'Cluster analysis', signals.base.RList, self.processclust) # creer un signal pour hclust
        self.inputs.addInput('id1', 'Dissimilarity (for Shepard plot)', signals.base.RMatrix, self.processdiss) # creer un signal pour dissimilarity object
		
        #Outputs
        self.outputs.addOutput('id0', 'Dissimilarity', signals.base.RMatrix) # should output dissimilaroty signal
        self.outputs.addOutput('id1', 'Cophenetic correlation', signals.base.RVariable)
        
        #GUI
        self.RFunctionParam_GUI_tabs = redRGUI.base.tabWidget(self.controlArea)
        #self.RFunctionParam_GUI_tabsDiagnostic = self.RFunctionParam_GUI_tabs.createTabPage(name = "Diagnostic",orientation='vertical')
        self.RFunctionParam_GUI_tabsPlot = self.RFunctionParam_GUI_tabs.createTabPage(name = "Plot",orientation='vertical')
        #self.RoutputWindow = redRGUI.base.textEdit(self.RFunctionParam_GUI_tabsDiagnostic, label = _("RoutputWindow"))
        self.plotArea = redRGUI.plotting.redRPlot(self.RFunctionParam_GUI_tabsPlot, label = "Plot", displayLabel = False)
        #self.plotArea.topArea.hide()
        
        #Commit
        self.commit = redRGUI.base.commitButton(self.bottomAreaRight, _("Commit"), alignment=Qt.AlignLeft, 
        callback = self.commitFunction, processOnInput=True)
        
        
    def processclust(self, data):
        if not self.require_librarys(["stats"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if data:
            self.RFunctionParam_clust=data.getData()
            self.data = data
            if self.commit.processOnInput():
                self.commitFunction()
        else:
            self.RFunctionParam_clust=''
            
    def processdiss(self, data):
        if not self.require_librarys(["stats"]):
            self.status.setText('R Libraries Not Loaded.')
            return
        if data:
            self.RFunctionParam_diss=data.getData()
            self.data = data
            if self.commit.processOnInput():
                self.commitFunction()
        else:
            self.RFunctionParam_diss=''

    def commitFunction(self):
        
        if unicode(self.RFunctionParam_clust) == '':
            self.status.setText('No data.')
            return
        if unicode(self.RFunctionParam_diss) == '':
            self.status.setText('No dissimilarity matrix connected. No cophenetic correlation will be computed. No Shepard plot will be generated.')
        
        self.R(self.Rvariables['cophenetic_dist']+'<-cophenetic('+unicode(self.RFunctionParam_clust)+')', wantType = 'NoConversion')
        
        if unicode(self.RFunctionParam_diss) != '':
            self.R(self.Rvariables['cophenetic_cor']+'<-cor('+unicode(self.RFunctionParam_diss)+', '+self.Rvariables['cophenetic_dist']+')', wantType = 'NoConversion')
            #self.RoutputWindow.clear()
            #tmp = self.R('paste("Cophenetic correlation:","\n",'+self.Rvariables['cophenetic_cor']+')')
            #self.RoutputWindow.insertHtml('<br><pre>'+tmp+'</pre>')
            self.plotArea.plotMultiple(query = 'distMat='+unicode(self.RFunctionParam_diss)+', copheneticDist='+self.Rvariables['cophenetic_dist'], function = 'sphepardCophCor') #plotMultiple used here instead of plot. I got an error with plot, avoided with plotMultiple.
        

        self.newData_diss = signals.base.RMatrix(self, data = self.Rvariables["cophenetic_dist"], checkVal=False)
        self.newData_cor = signals.base.RVariable(self, data = self.Rvariables["cophenetic_cor"], checkVal=False)
        self.rSend("id0", self.newData_diss)
        self.rSend("id1", self.newData_cor)